
package ogame.utilities.research;

import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author scchang
 */
public class Research extends HashMap<ResearchType, Integer>{
    public Research(){
        super();
        for(ResearchType type: ResearchType.values()){
            // Initialize all to 0
            this.put(type, 0);
        }
    }
    
    public String toString(){
        String output = "";
        for(ResearchType type: ResearchType.values()){
            output += type + " : " + this.get(type) + '\n';
        }
        return output;
    }
    
    public static Research parseResearch(byte[] input){
        int index = 0;
        Research research = new Research();
        for(ResearchType type: ResearchType.values()){
            research.put(type, (int)input[index]);
            index++;
        }
        return research;
    }
    
    public byte[] encode(){
        // This is to ensure some validlity there are better ways
        ArrayList<Byte> theList = new ArrayList<>(ResearchType.values().length);
        for(ResearchType type: ResearchType.values()){
            theList.add(Byte.parseByte("" + this.get(type)));
        }
        
        Byte[] resultByte = new Byte[theList.size()];
        resultByte = theList.toArray(resultByte);
        
        byte[] result = new byte[theList.size()];
        for(int i = 0; i < result.length; ++i){
            result[i] = resultByte[i];
        }
        return result;
    }
    
    public static boolean unitTest(){
        Research research = new Research();
        int i = 0;
        for(ResearchType type : ResearchType.values()){
            research.put(type, i);
            i++;
        }
        
        Research result = Research.parseResearch(research.encode());
        i = 0;
        for(ResearchType type : ResearchType.values()){
            if(result.get(type) != i){
                System.out.format("With type: " + type + " with :%d\n", result.get(type));
                return false;
            }
            i++;
        }
        
        result = Research.parseResearch(new Research().encode());
        for(ResearchType type : ResearchType.values()){
            if(result.get(type) != 0){
                System.out.println("With type: " + type + " got: " + result.get(type) +
                        ".  Expected 0.");
                return false;
            }
        }
        
        return true;
    }
}
